var config = require('../config');
var storage = require('../util/storage');

/**
 * 微信登录-静默方式Silent
 */
var silentLogin= function wxLogin(){
  /*
    * 获取用户openid
    * 1、先通过wx.login获取一个临时凭证code
    * 2、然后我们拿这个code去自己的服务器换取用户openid
    */
    wx.login({
      success: function (res) {
        var code = res.code;//发送给服务器的code
        if(!code||'the code is a mock one'==code){
              console.log("获取用户登录态失败！%s",code);
        }else{

              wx.request({
                url: config.service.apiUrl + '/api/login?code=' + code,
                header: {
                  'content-type': 'application/json'
                },
                success: function (res) {
                  if (res.data.code == 0) {
                    var info = res.data.data;
                    console.log('openid=%s',info.openid);
                    //可以把openid保存到本地缓存，方便以后调用
                    storage.put('openid', info.openid);
                    storage.put('sessionKey', info.sessionKey);
                    storage.put('unionid', info.unionid);
                     // 服务器后台这个参数
                    storage.put('needProfileAuth', info.needProfile);
                    storage.put('needPhoneAuth', info.needPhone);

                  } else {
      
                  }
                }
              });
        }

      },
      fail: function (error) {
        console.log('login failed ' + error);
      }
    }) //
  
};

var saveAuthProfile= function saveAuthProfile(userInfo){
  storage.put('userInfo',userInfo);
  var temp=userInfo;
  temp.sessionKey=storage.get('sessionKey');
  temp.openid=storage.get('openid');
  wx.request({
        url: config.service.apiUrl + '/api/user/saveProfile',
        data:temp,
        header: {
            "Content-Type":"application/json;charset=UTF-8"
        },
      method: "POST",
      dataType: 'json',
        success: function (res) {
            if (res.data.code == 0) {
                storage.put('needProfileAuth',false);
                console.log('saved profile');
            } else {
               console.log('save profile failed');
            }
        }
    });

};


module.exports = {
      silentLogin: silentLogin,
      saveAuthProfile: saveAuthProfile
};